package com.bitsemart;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.bitsemart.VisorVideojuego.VisorVideojuegoCliente;
import com.bitsemart.dialogos.SortDialogFragment;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

/**
 * Created by Javier on 28/04/2015.
 */
public class ListaCarrito extends ActionBarActivity {

    private TextView titulo;
    private Toolbar toolbar;
    private ArrayList<Videojuego> list = new ArrayList<>();
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private BDLocal bdlocal;
    private BDHendrix bdhendrix;
    private ArrayList<Integer> arrayEnteros;
    private static AlertDialog.Builder builder;
    private static AlertDialog dialog;
    @Override
    protected void onStart(){
        super.onStart();
        populateFields();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //SETUP LAYOUT
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lista_carrito);
        //ABRIMOS BDLOCAL
        bdlocal = new BDLocal(this);
        bdlocal.open();
        //SETUP BD
        try {
            InputStream in = getAssets().open("properties.oracle");
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            bdhendrix = new BDHendrix(reader.readLine(), reader.readLine(), this);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //SETUP ACTION BAR
        toolbar = (Toolbar) findViewById(R.id.carrito_action_bar);
        toolbar.setTitle("Bits-e-Mart");
        setSupportActionBar(toolbar);

        //SETUP TEXTVIEW
        titulo = (TextView) findViewById(R.id.total_carrito);

        //SETUP RECYCLER VIEW
            /* //DEBUG
            list = new ArrayList<Videojuego>();
            for (int i = 0; i<60; i++) {
                list.add(new Videojuego("Videojuego" + i, 2015, 60, "Shooter", "EASOFT", "Descripcion" + i, null));
            } */
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_carrito);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(mLayoutManager);
//        mAdapter = new VideojuegoAdapter(list);
//        mRecyclerView.setAdapter(mAdapter);

        mRecyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        verJuego(position);
                    }
                })
        );

        populateFields();
    }

    private void populateFields() {
        arrayEnteros = bdlocal.fetchAllVideojuegos();
        Button volver = (Button) findViewById(R.id.volver_cart);
        volver.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                setResult(RESULT_OK);
                finish();
            }
        });


        try {
            updateList();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void checkout() {
        Intent i = new Intent(this, Checkout.class);
        String msg = "";
        for (Videojuego vj : list) {
            msg = msg + "Titulo: " + vj.getTitulo() + "\nPrecio: " + vj.getPrecio()/100.0 + "\n\n";
        }
        i.putExtra("LISTAJUEGOS", msg);
        startActivityForResult(i, 0);
    }

    private void verJuego(int pos) {
        Videojuego seleccionado = list.get(pos);
        Intent i = new Intent(this, VisorVideojuegoCliente.class);
        i.putExtra("ID", seleccionado.getId());
        i.putExtra("TITULO", seleccionado.getTitulo());
        i.putExtra("DESARROLLADOR", seleccionado.getDesarrollador());
        i.putExtra("DESCRIPCION", seleccionado.getDescripcion());
        i.putExtra("GENERO", seleccionado.getGenero());
        i.putExtra("NUM_DESCARGAS", seleccionado.getNumDescargas());
        i.putExtra("PRECIO", seleccionado.getPrecio());
        i.putExtra("YEAR", seleccionado.getYear());
        i.putExtra("IMAGE", seleccionado.getImagen());
        startActivityForResult(i, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == 0) {
            populateFields();
        }
    }

    private int sumarPrecio() {
        int total = 0;
        for (Videojuego videojuego : list) {
            total += videojuego.getPrecio();
        }
        return total;
    }

    public void updateList() throws ExecutionException, InterruptedException {
        if(isNetworkAvailable())
        {
            list=bdhendrix.obtenerVideojuegos(arrayEnteros);
            mAdapter = new VideojuegoAdapter(list);

            mRecyclerView.setAdapter(mAdapter);


            Button comprar = (Button) findViewById(R.id.botoncomprar);
            if (arrayEnteros.size() == 0) {
                comprar.setEnabled(false);

            }
            comprar.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    checkout();
                }
            });
            titulo.setText(String.format("Precio total: %.2f euros", sumarPrecio() * 0.01));

        }
        else {
            builder = new AlertDialog.Builder(this);
            builder.setTitle("Conexión no disponible");
            builder.setMessage("No dispone de conexión a internet.\nNetwork Unavailable!");
            ;
            builder.setPositiveButton("Reintentar", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    dialog.dismiss();
                    try {
                        updateList();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            dialog = builder.create();
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }
    }
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}
